Skip to content


tag  jupyter  tips  ai  deep learning  beginner  regression  reinforcement learning  q learning  gym  gymnasium  ardupilot  None  ros2  dds  micro ros  xrce  sitl  plugin  SITL  debug  rangefinder  pymavlink  mavros  gazebo  distance sensor  system_time  timesync  cmake  gtest  ctest  101  cpp  c++  format  fmt  multithreading  spdlog  cyclonedds  eprosima  fastdds  simulation  config  ignition  bridge  sdf  ign-transport  camera  sensors  lidar  aptly  apt  repository  repo  local  mirror  encryption  pgp  docker  container  state  networking  network  nvidia  python  app  devcontainer  gui  tutorial  multi-stage  stage  docker compose  git  bundle  submodules  github  hooks  pre-commit  lxd  lxc  x11  profile  vscode  marpit  presentation  marp  markdown  mermaid  mkdocs  video  ffmpeg  gstreamer  cheat-sheet  sdp  v4l2loopback  gi  kml  geo  gis  spatial  gdal  ogr  raster  vector  snippets  cheat Sheet  asyncio  future  click  cli  dev container  deb  debian  package  setup  stdeb  project  hydra  yaml  configuration  numpy  template  black  isort  templates  cookiecutter  docs  project document  docstrings  flake8  linter  git-hook  mypy  unittest  pytest  pylint  from a-z  logging  pytest.ini  mock  iterator  generator  yml  tuple  namedtuple  typing  annotation  typever  pyzmq  zmq  msgpack  action  namespace  remap  control2  ros2_control  effort  velocity  gdb  qos  plugins  msg  node  zero-copy  shm  algorithm  calibration  diff  pid  dev  colcon  colcon_cd  settings  behavior  py_trees  bt  behavior_trees  blackboard  plot  visualization  debugging  diagnostic  DiagnosticTask  diagnostics  tutorials  gst  math  apm  rat_runtime_monitor  bag  rosbag  rosbags  tools  ros  web  rosbridge  vue  binding  discovery  gazebo-classic  launch  spawn  model  cook  gps  imu  ray  gazebo_ros_ray_sensor  ultrsonic  range  ultrasonic  gazebo classic  wrench  odom  ign  gz  xacro  ros_ign  diff_drive  odometry  joint_state  argument  OpaqueFunction  DeclareLaunchArgument  LaunchConfiguration  tmux  nav  slam  test  rclpy  goal abort  cancel goal  action client  action server  custom messages  executor  MultiThreadedExecutor  SingleThreadedExecutor  param  dynamic-reconfigure  service  client  setup.py  package.xml  parameter  parameters  custom  msgs  executers  pub  sub  rqt  rviz  rviz2  pose  marker  tf2  local_setup  rosdep  package manager  project settings  vcstool  urdf  robot_state_publisher  urdf_to_graphiz  joint  link  zenoh  tags  hands on  webinar  cross-compiler  nano  rpi  texture  joints  tmuxp  loop device  rootfs  embedded  zah  linux  rm  ubuntu  sudo  sudoers  nopasswd  visudo  udev  key  gpg  sign  commands  update-alternative  ip  ss  netstat  snap  deploy  ssh  systemd  socat  serial  udp  tc  mtu  select  robotics  path planning  trajectory  speed  kalman_filter  kalman  filter  control  code  extensions  json  schema  yocto  poky  qemu  projects  courses to follow  drone  quad  uav  design  vrx  buoyancy 

PyTest - Mocking#

mocking

A mock object is a simulated object that mimics the behavior of the smallest testable parts of an application in controlled ways. It’s replace of one or more function or objects calls

A mock function call return a predefined value immediately without doing any work

In Python mocking implement by unittest.mock module

demo1#

How To Mock Patch A Function

demo.py
from random import randint

def func_under_test():
    r = randint(1, 8)
    return r
test_demo.py
from demo import func_under_test
from unittest import mock

@mock.patch("demo.randint", return_value=7, autospec=True)
def test_with_mock(mock_randint):
    r = func_under_test()
    assert r == 7

patch

Patch the thing where it used not where it’s import In the above example we patch demo.randint and not random.randint

autospec

autospec


Simple demo#

project
search
  ├── tutorial
   ├── __init__.py
   └── demo.py
  └── tests
   └── test_demo.py
demo.py
# method to mock
def get_number() -> int:
    return 5

# function under test
def add(a: int) -> int:
    b = get_number()
    return a + b
test_demo.py
from unittest.mock import patch, MagicMock

@patch("tutorial.demo.get_number")
def test_add_mock(mock_get_number: MagicMock) -> None:
    mock_get_number.return_value = 2
    result = add(1)
    assert result == 3

Warning

@path full name of the function or class to patch module_name.func_name for example to path get_number function in demo module. @patch("demo.get_number")


Mock with parametrize#

  • Set mock return_value from parameter
demo.py
from random import randint

def get_random():
    return randint(1, 10)


def good_random():
    r = get_random()
    if r > 7:
        return "win"
    else:
        return "lose"
test_demo.py
import pytest
from unittest import mock
from demo import good_random


@pytest.mark.parametrize("_input, expected", [(8, "win"), (5, "lose")])
@mock.patch("demo.get_random")
def test_good_random(mock_get_random, _input, expected):
    mock_get_random.return_value = _input
    result = good_random()
    assert result == expected

MagicMock#

Provide a simple mocking interface that allow to mock partial real object that we wont to patch

return_value#

allows you to choose what the patched callable returns, usually we return the same type of the real callable but controllable

side_effect#

Change the behavior of the mock

side_effect = Iterable#

yield the values from defined iterable on subsequent call

>>> from unittest.mock import MagicMock
>>> m = MagicMock()
>>> m.get_data.side_effect = [5, 10, 15]
>>> m.get_data()
5
>>> m.get_data()
10
>>> m.get_data()
15
from unittest.mock import patch

def my_input() -> int:
    return 1

def method_to_test():
    a = my_input()
    b = my_input()
    return a+b


@patch("test_demo.my_input")
def test_multiple(mock_my_input):
    mock_my_input.side_effect = [1, 2]
    result = method_to_test()
    assert result == 3
side_effect = Exception#
m.check.side_effect = Exception("custom exception")
>>> m.check()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.8/unittest/mock.py", 
  ...
    raise effect
Exception: custom exception
ide_effect = callable#

The callable will be executed on each call with the parameters passed when calling the mocked method

>>> def call_me(name):
...     print(name)
... 
>>> m.run_call.side_effect = call_me
>>> m.run_call("a")
a
>>> m.run_call("b")
b
>>> m.run_call.call_count
2
>>> m.run_call("b")
b
>>> m.run_call.call_count
3

Reference#